package com.kabuda.zhugehot200;

/**
 * @author kabuda
 * @date 2025-03-23 20:40
 * @description
 */
public class t794_有效的井字游戏 {
    public static void main(String[] args) {
        System.out.println(validTicTacToe(new String[]{"XOX", "O O", "XOX"}));
        System.out.println(validTicTacToe(new String[]{"O  ","   ","   "}));
    }


    /**
     * 分类进行穷举
     *
     * @param board 棋盘情况
     * @return
     */
    public static boolean validTicTacToe(String[] board) {
        //x先手，o后手
        //x胜利：xCount-oCount==1
        //o胜利：xCount-oCount==0
        //胜负未分：xCount-oCount!=1 xCount-oCount!=0

        //1.计算棋子数量
        int xCount = 0;
        int oCount = 0;
        for (String row : board) {
            for (char c : row.toCharArray()) {
                if (c == 'X') {
                    xCount++;
                }
                if (c == 'O') {
                    oCount++;
                }
            }
        }

        //胜负未分：xCount-oCount!=1 xCount-oCount!=0
        if (xCount != oCount && xCount - oCount != 1) {
            return false;
        }

        //x胜利：xCount-oCount==1

        if (win(board, "X") && xCount - oCount != 1) {
            return false;
        }

        //o胜利：xCount-oCount==0
        if (win(board, "O") && xCount != oCount) {
            return false;
        }
        return true;
    }

    public static boolean win(String[] board, String x) {
        //3*3 棋盘
        for (int i = 0; i < 3; i++) {
            //三横
             if (board[i].equals(x + x + x)) {
                return true;
            }
            //三竖
            if (x.equals(board[0].charAt(i)+"")&&x.equals(board[1].charAt(i)+"")&&x.equals(board[2].charAt(i)+"")) {
                return true;
            }
            //对角
            if (x.equals(board[0].charAt(0)+"")&&x.equals(board[1].charAt(1)+"")&&x.equals(board[2].charAt(2)+"")
                    ||x.equals(board[0].charAt(2)+"")&&x.equals(board[1].charAt(1)+"")&&x.equals(board[2].charAt(0)+"")) {
                return true;
            }
        }
        return false;
    }
}
